<!DOCTYPE HTML>
<html>
<head>
    <title> 搜索表单</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link href="../static_pc/assets3/css/bs3/dpl-min.css" rel="stylesheet" type="text/css"/>
    <link href="../static_pc/assets3/css/bs3/bui-min.css" rel="stylesheet" type="text/css"/>
    <!-- <link href="../static_pc/assets/css/dpl-min.css" rel="stylesheet" type="text/css" />
    <link href="../static_pc/assets/css/bui-min.css" rel="stylesheet" type="text/css" /> -->
    <link href="../static_pc/assets/css/page-min.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" href="../static_pc/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css">
    <style>
        /**内容超出 出现滚动条 **/
        .bui-stdmod-body {
            overflow-x: hidden;
            overflow-y: auto;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <form id="searchForm" class="form-horizontal span24">
            <div class="row">
                <div class="control-group span8">
                    <label class="control-label">角色名</label>

                    <div class="controls">
                        <input type="text" class="control-text" name="key" placeholder="角色名">
                        <input type="text" name="aaa" style="display: none;">
                    </div>
                </div>
                <div class="span3 offset">
                    <button type="button" id="btnSearch" class="button button-primary">搜索</button>
                </div>
            </div>
        </form>
    </div>
    <div class="search-grid-container">
        <div id="grid"></div>
    </div>

</div>


<div id="content" class="hide">
    <form id="J_Form" class="form-horizontal" action="" method="post">
        <input type="hidden" name="id">

        <div class="row">
            <input name="ids" type="hidden" data-rules="{required:true}" class="input-normal control-text">
        </div>
        <div class="row">
            <div class="control-group span8">
                <div class="controls">
                    <div id="treeDemo" class="ztree" style="overflow:auto;"></div>
                </div>
            </div>
        </div>
    </form>
</div>

<div id="content2" class="hide">
    <form id="J_Form2" class="form-horizontal" action="" method="post">
        <input type="hidden" name="id">

        <div class="row">
            <div class="control-group span8">
                <label class="control-label"><s>*</s>角色名</label>

                <div class="controls">
                    <input name="roleName" type="text" data-rules="{required:true}" class="input-normal control-text">
                </div>
            </div>
        </div>
    </form>
</div>
<script type="text/javascript" src="../static_pc/common/jquery.min-2.1.3.js"></script>
<script type="text/javascript" src="../static_pc/layer/layer.js"></script>
<script type="text/javascript" src="../static_pc/assets/js/bui.js"></script>
<script type="text/javascript" src="../static_pc/assets/js/config.js"></script>
<script type="text/javascript" src="../static_pc/zTree/js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="../static_pc/zTree/js/jquery.ztree.excheck.js"></script>
<script type="text/javascript">
    var treeObj;
    var setting = {
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        view: {}
    };

    var zNodes = [];

    BUI.use(['common/search', 'bui/overlay'], function (Search, Grid, Data, overlay) {
        var Mask = BUI.Mask, Overlay = BUI.Overlay,
                Grid = BUI.Grid,
                columns = [
                    {title: '角色名', dataIndex: 'roleName', elCls: 'center'},
                    {
                        title: '操作', dataIndex: '', elCls: 'center', renderer: function (value, obj) {
                        var authStr = '<span class="grid-command btn-edit" title="权限">权限</span>';
                        return authStr;
                    }
                    }
                ],
                editing = new Grid.Plugins.DialogEditing({
                    contentId: 'content',
                    triggerCls: 'btn-edit1',
                    editor: {
                        width: 300,
                        height: 400,
                        title: '分配权限',
                        success: function () {
                            var edtor = this,
                                    form = edtor.get('form'),
                                    editType = editing.get('editType');//add 或者 edit
                            var nodes = treeObj.getCheckedNodes(true);
                            var tmpNode;
                            var ids = "";
                            for (var i = 0; i < nodes.length; i++) {
                                tmpNode = nodes[i];
                                if (i != nodes.length - 1) {
                                    ids += tmpNode.id + ",";
                                } else {
                                    ids += tmpNode.id;
                                }
                            }
                            $("[name='ids']").val(ids);//赋值给控件
                            //alert(ids);
                            //检验
                            form.valid();
                            if (form.isValid()) {
                                layer.load();
                                form.ajaxSubmit({ //表单异步提交
                                    url: "../api/auth/updAuth",
                                    dataType: "json",
                                    type: "post",
                                    success: function (data) {
                                        layer.closeAll('loading');
                                        if (data.hasError) { //返回的数据是 {hasError : fasle,error : 'xxxx',field : 'xxx'},也可以是任意格式的数据如 ： {success : false,'error' : 'xxxxx'}
                                            if (data.errType == "NOAUTH") {
                                                edtor.close();
                                            }
                                            BUI.Message.Alert(data.error, 'warning');
                                        } else {
                                            edtor.close();
                                            /*BUI.Message.Alert(data.error, function () {
                                                //edtor.close();
                                            }, 'info');*/
                                        }
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        layer.closeAll('loading');
                                        BUI.Message.Alert("系统繁忙，请稍后" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + textStatus, 'warning');
                                    }
                                });
                            }
                        }
                    }
                }), editing2 = new Grid.Plugins.DialogEditing({
                    contentId: 'content2',
                    triggerCls: 'btn-edit2',
                    editor: {
                        width: 400,
                        title: '编辑',
                        success: function () {
                            var edtor = this,
                                    form = edtor.get('form'),
                                    editType = editing2.get('editType');//add 或者 edit
                            var url = "";
                            if (editType == "add") {
                                url = "../api/auth/saveRole";
                            } else {
                                url = "../api/auth/updateRole";
                            }
                            //检验
                            form.valid();
                            if (form.isValid()) {
                                layer.load();
                                form.ajaxSubmit({ //表单异步提交
                                    url: url,
                                    dataType: "json",
                                    type: "post",
                                    success: function (data) {
                                        layer.closeAll('loading');
                                        if (data.hasError) { //返回的数据是 {hasError : fasle,error : 'xxxx',field : 'xxx'},也可以是任意格式的数据如 ： {success : false,'error' : 'xxxxx'}
                                            if (data.errType == "NOAUTH") {
                                                edtor.close();
                                            }
                                            BUI.Message.Alert(data.error, 'warning');
                                        } else {
                                            store.load();
                                            edtor.close();
                                            /*BUI.Message.Alert(data.error, function () {
                                                //edtor.close();
                                            }, 'info');*/
                                        }
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        layer.closeAll('loading');
                                        BUI.Message.Alert("系统繁忙，请稍后" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + textStatus, 'warning');
                                    }
                                });
                            }
                        }
                    }
                }),
                store = Search.createStore('../api/auth/listRoles', {
                    proxy: {
                        save: { //也可以是一个字符串，那么增删改，都会往那么路径提交数据，同时附加参数saveType
                            /* addUrl : '${pageContext.request.contextPath}/admin/addAdm.shtml',
                             updateUrl : '${pageContext.request.contextPath}/admin/updAdm.shtml',
                             removeUrl : '${pageContext.request.contextPath}/admin/delAdm.shtml' */
                        },
                        method: 'POST'
                    },
                    pageIndex: 0,
                    pageSize: 10,
                    autoSync: true //保存数据后，自动更新
                }),
                gridCfg = Search.createGridCfg(columns, {
                    forceFit: true,
                    emptyDataTpl : '<div class="centered"><img alt="Crying" src="http://img03.taobaocdn.com/tps/i3/T1amCdXhXqXXXXXXXX-60-67.png"><h2>查询的数据不存在</h2></div>',
                    tbar: {
                        items: [
                            {text: '<i class="icon-plus"></i>新建', btnCls: 'button button-small', handler: addFunction},
                            {text: '<i class="icon-edit"></i>编辑', btnCls: 'button button-small', handler: updFunction},
                            {text: '<i class="icon-remove"></i>删除', btnCls: 'button button-small', handler: delFunction}
                        ]
                    },
                    //loadMask: true, //加载数据时显示屏蔽层
                    plugins: [editing, editing2, BUI.Grid.Plugins.CheckSelection] // 插件形式引入多选表格
                });

        var search = new Search({
                    store: store,
                    gridCfg: gridCfg
                }),
                grid = search.get('grid');

        editing.on('editorshow', function (ev) {
            var type = ev.editType; //add ,edit
            //record = editing.get('record');
        });

        function addFunction() {
            var newData = {isNew: true}; //标志是新增加的记录
            editing2.add(newData, 'data'); //添加记录后，直接编辑
        }

        function updFunction() {
            var selections = grid.getSelection();
            var ids = [];
            BUI.each(selections, function (selections) {
                ids.push(selections.id);
            });

            if (ids.length > 1) {
                BUI.Message.Alert('只能选择一条记录', 'warning');
            } else if (ids.length <= 0) {
                BUI.Message.Alert('请选择要编辑的记录', 'warning');
            } else {
                //alert(JSON.stringify(selections));
                editing2.edit(selections[0]);
            }
        }

        //删除操作
        function delFunction() {
            var selections = grid.getSelection();
            //alert(JSON.stringify(selections));
            delItems(selections);
        }

        function delItems(items) {
            var ids = [];
            BUI.each(items, function (item) {
                ids.push(item.id);
            });
            if (ids.length) {
                BUI.Message.Confirm('确认要删除选中的记录么？', function () {
                    layer.load();
                    $.ajax({
                        url: "../api/auth/removeRole",
                        data: {"ids": ids.toString()},
                        dataType: "json",
                        type: "post",
                        async: true,
                        success: function (data) {
                            layer.closeAll('loading');
                            if (!data.hasError) {
                                store.load();
                            } else {
                                BUI.Message.Alert(data.error, 'warning');
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.closeAll('loading');
                            BUI.Message.Alert("系统繁忙，请稍后" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + textStatus, 'warning');
                        }
                    });
                }, 'question');
            } else {
                BUI.Message.Alert("请选择记录", function () {
                }, 'warning');
            }
        }

        //监听事件
        grid.on('cellclick', function (ev) {
            $("[name='ids']").val("");
            $.fn.zTree.destroy("treeDemo");
            var sender = $(ev.domTarget); //点击的Dom
            if (sender.hasClass('btn-edit')) {
                var record = ev.record;
                layer.load();
                $.ajax({
                    url: "../api/auth/loadAuth",
                    data: {"roleId": record.id},
                    dataType: "json",
                    type: "post",
                    async: true,
                    success: function (data) {
                        if (!data.hasError) {
                            zNodes = eval('('+data.object+')');
                            treeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                            editing.edit(record);
                            layer.closeAll('loading');
                        } else {
                            BUI.Message.Alert(data.error, 'warning');
                        }
                        layer.closeAll('loading');
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.closeAll('loading');
                        BUI.Message.Alert("系统繁忙，请稍后" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + textStatus, 'warning');
                    }
                });

            }
        });
    });
</script>
</body>
</html>  